package com.lzx.iteam.util;

import android.content.*;
import android.content.Entity.NamedContentValues;
import android.net.Uri;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.*;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.RawContactsEntity;
import android.text.TextUtils;
import android.util.Log;
import com.lzx.iteam.bean.NameCardContact;
import com.lzx.iteam.bean.NameCardContact.KeyValue;
import com.lzx.iteam.contactssearch.ContactsDBReader;
import com.lzx.iteam.contactssearch.ContactsDBReader.GroupInfo;
import com.lzx.iteam.contactssearch.conversion.PinyinSearch;
import com.lzx.iteam.contactssearch.conversion.PinyinSearch.ContactInfoNode;
import com.lzx.iteam.engine.observer.FreshContactObserver;
import com.lzx.iteam.json.JSONParser;
import com.lzx.iteam.json.ParseException;
import com.lzx.iteam.net.AsynHttpClient;
import org.apache.http.util.EncodingUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.*;

public class NameCardUtil {

    public static final String LAST_NAME = "lastname";
    public static final String MIDDLE_NAME = "middlename";
    public static final String FIRST_NAME = "firstname";
    public static final String IMAGE = "image";

    public static final String DPHONES = "dphones";
    public static final String DEMAILS = "demails";

    public static final String JOB_TITLE = "jobtitle";
    public static final String ORGANIZATION = "organization";
    public static final String DEPARTMENT = "department";

    public static final String NICKNAME = "nickname";
    public static final String DADDRESSES = "daddresses";
    public static final String DGROUPS = "dgroups";
    public static final String DURLS = "durls";
    public static final String NOTE = "note";
    public static final String DONTREPLY = "dontreply";

    public static void jsonToObject(NameCardContact contact, JSONObject nameCard)
            throws JSONException, ParseException {

        // name
        if (nameCard.has(FIRST_NAME)) {
            String firstName = nameCard.getString(FIRST_NAME);
            firstName = EncodingUtils.getString(Base64.decode(firstName, Base64.NO_WRAP),
                    "UTF-8");
            contact.firstName = firstName;
        }

        if (nameCard.has(MIDDLE_NAME)) {
            String middleName = nameCard.getString(MIDDLE_NAME);
            middleName = EncodingUtils.getString(Base64.decode(middleName, Base64.NO_WRAP),
                    "UTF-8");
            contact.middleName = middleName;
        }

        if (nameCard.has(LAST_NAME)) {
            String lastName = nameCard.getString(LAST_NAME);
            lastName = EncodingUtils.getString(Base64.decode(lastName, Base64.NO_WRAP),
                    "UTF-8");
            contact.lastName = lastName;
        }

        if (nameCard.has(NOTE)) {
            String note = nameCard.getString(NOTE);
            note = EncodingUtils.getString(Base64.decode(note, Base64.NO_WRAP), "UTF-8");
            if (!StringUtil.isEmpty(note)) {
                contact.note = note;
            }
        }

        if (nameCard.has(DEPARTMENT)) {
            String department = nameCard.getString(DEPARTMENT);
            department = EncodingUtils
                    .getString(Base64.decode(department, Base64.NO_WRAP), "UTF-8");
            if (!StringUtil.isEmpty(department)) {
                contact.department = department;
            }
        }

        if (nameCard.has(DADDRESSES)) {
            JSONParser parser = new JSONParser();
            String address = nameCard.getString(DADDRESSES);
            if (!StringUtil.isEmpty(address)) {
                com.lzx.iteam.json.JSONArray array = (com.lzx.iteam.json.JSONArray) parser.parse(address);
                int arraySize = 0;
                if (array != null) {
                    arraySize = array.size();
                }
                int count = 0;
                contact.address = new HashMap<String, String[]>();
                while (count < (arraySize)) {
                    com.lzx.iteam.json.JSONArray innerArray = (com.lzx.iteam.json.JSONArray) parser
                            .parse(array.get(count).toString());
                    String[] addressArray = new String[innerArray.size()];
                    for (int inner = 0; inner < innerArray.size(); inner++) {
                        addressArray[inner] = EncodingUtils.getString(
                                Base64.decode(innerArray.get(inner).toString(), Base64.NO_WRAP),
                                "UTF-8");
                    }
                    String label = EncodingUtils.getString(
                            Base64.decode(array.get(count + 1).toString(), Base64.NO_WRAP),
                            "UTF-8");
                    contact.address.put(label, addressArray);
                    count += 2;
                }
            }
        }

        if (nameCard.has(IMAGE)) {
            String photo = null;
            try {
                photo = nameCard.getString(IMAGE);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            byte[] pic = Base64.decode(photo, Base64.DEFAULT);
            if (pic == null || pic.length == 0) {
                contact.pic = null;
            } else {
                contact.pic = pic;
            }
        }

        if (nameCard.has(JOB_TITLE)) {
            String jobtitle = nameCard.getString(JOB_TITLE);
            jobtitle = EncodingUtils.getString(Base64.decode(jobtitle, Base64.NO_WRAP), "UTF-8");
            if (!StringUtil.isEmpty(jobtitle)) {
                contact.jobTitle = jobtitle;
            }
        }

        if (nameCard.has(DPHONES)) {
            String dphones = nameCard.getString(DPHONES);
            JSONParser parser = new JSONParser();
            if (!StringUtil.isEmpty(dphones)) {
                com.lzx.iteam.json.JSONArray array = (com.lzx.iteam.json.JSONArray) parser.parse(dphones);
                String[] phonesArray = null;
                int arraySize = 0;
                if (array != null)
                    arraySize = array.size();
                if (arraySize > 0) {
                    arraySize = array.size();
                    phonesArray = new String[arraySize];
                    for (int arrayIndex = 0; arrayIndex < arraySize; arrayIndex++) {
                        phonesArray[arrayIndex] = EncodingUtils.getString(
                                Base64.decode(array.get(arrayIndex).toString(), Base64.NO_WRAP),
                                "UTF-8");
                    }
                    int count = 0;
                    while (count < (arraySize - 1)) {
                        KeyValue obj = new KeyValue();
                        obj.value = phonesArray[count++];
                        obj.key = phonesArray[count++];
                        contact.phoneArray.add(obj);
                    }
                }
            }
        }

        if (nameCard.has(ORGANIZATION)) {
            String organization = nameCard.getString(ORGANIZATION);
            organization = EncodingUtils.getString(Base64.decode(organization, Base64.NO_WRAP),
                    "UTF-8");
            if (!StringUtil.isEmpty(organization)) {
                contact.organization = organization;
            }
        }

        if (nameCard.has(DURLS)) {
            JSONParser parser = new JSONParser();
            String durls = nameCard.getString(DURLS);
            if (!StringUtil.isEmpty(durls)) {
                com.lzx.iteam.json.JSONArray array = (com.lzx.iteam.json.JSONArray) parser.parse(durls);
                int arraySize = 0;
                String[] urlArray = null;
                if (array != null)
                    arraySize = array.size();
                if (arraySize > 0) {
                    urlArray = new String[arraySize];
                    for (int arrayIndex = 0; arrayIndex < arraySize; arrayIndex++) {
                        urlArray[arrayIndex] = EncodingUtils.getString(
                                Base64.decode(array.get(arrayIndex).toString(), Base64.NO_WRAP),
                                "UTF-8");
                    }

                    int count = 0;
                    while (count < (arraySize - 1)) {
                        KeyValue obj = new KeyValue();
                        obj.value = urlArray[count++];
                        obj.key = urlArray[count++];
                        contact.urlArray.add(obj);
                    }
                }
            }
        }

        if (nameCard.has(DEMAILS)) {
            String demails = nameCard.getString(DEMAILS);
            JSONParser parser = new JSONParser();
            if (!StringUtil.isEmpty(demails)) {
                com.lzx.iteam.json.JSONArray array =
                        (com.lzx.iteam.json.JSONArray) parser.parse(demails);
                String[] emailArray = null;
                int arraySize = 0;
                if (array != null)
                    arraySize = array.size();
                if (arraySize > 0) {
                    emailArray = new String[arraySize];
                    for (int arrayIndex = 0; arrayIndex < arraySize; arrayIndex++) {
                        emailArray[arrayIndex] = EncodingUtils.getString(
                                Base64.decode(array.get(arrayIndex).toString(), Base64.NO_WRAP),
                                "UTF-8");
                    }
                    int count = 0;
                    while (count < (arraySize - 1)) {
                        KeyValue obj = new KeyValue();
                        obj.value = emailArray[count++];
                        obj.key = emailArray[count++];
                        contact.emailArray.add(obj);
                    }
                }
            }
        }

        // 分组信息
        if (nameCard.has(DGROUPS)) {
            String dgroups = nameCard.getString(DGROUPS);
            JSONParser parser = new JSONParser();
            if (!StringUtil.isEmpty(dgroups)) {
                com.lzx.iteam.json.JSONArray array = (com.lzx.iteam.json.JSONArray) parser.parse(dgroups);
                int arraySize = 0;
                if (array != null)
                    arraySize = array.size();
                if (arraySize > 0) {
                    contact.groupNameArray = new String[arraySize];
                    for (int arrayIndex = 0; arrayIndex < arraySize; arrayIndex++) {
                        contact.groupNameArray[arrayIndex] = array.get(arrayIndex).toString();
                    }
                }
            }
        }

        if (nameCard.has(DONTREPLY)) {
            String auto = nameCard.getString(DONTREPLY);
            if (auto.equals("auto")) {
                contact.huidizi = true;
            }
        }
    }

    private static void sendPhoto(ContentValues cv, JSONObject userNameCard) throws JSONException {
        if (cv.containsKey(Photo.PHOTO)) {
            byte[] bytes = cv.getAsByteArray(Photo.PHOTO);
            String pic = Base64.encodeToString(bytes, Base64.NO_WRAP);
            userNameCard.put(IMAGE, pic);
        }
    }

    @SuppressWarnings("unchecked")
    private static void sendEmail(ContentValues cv, JSONObject userNameCard) throws JSONException {
        com.lzx.iteam.json.JSONArray array = new com.lzx.iteam.json.JSONArray();

        String emailAddr = cv.getAsString(Email.DATA);
        emailAddr = Base64.encodeToString(emailAddr.getBytes(), Base64.NO_WRAP);
        array.add(emailAddr);

        if (cv.containsKey(Email.TYPE) && cv.getAsInteger(Email.TYPE) != null) {
            int type = cv.getAsInteger(Email.TYPE);
            String label = emailType2StrLabel(type);
            label = Base64.encodeToString(label.getBytes(), Base64.NO_WRAP);
            array.add(label);
        }

        String jsonString = array.toJSONString();
        userNameCard.put(DEMAILS, jsonString);
    }

    @SuppressWarnings("unchecked")
    private static void parseEmail(ContentValues cv, com.lzx.iteam.json.JSONArray array) throws JSONException {

        String emailAddr = cv.getAsString(Email.DATA);
        emailAddr = Base64.encodeToString(emailAddr.getBytes(), Base64.NO_WRAP);
        array.add(emailAddr);

        if (cv.containsKey(Email.TYPE) && cv.getAsInteger(Email.TYPE) != null) {
            int type = cv.getAsInteger(Email.TYPE);
            String label = emailType2StrLabel(type);
            label = Base64.encodeToString(label.getBytes(), Base64.NO_WRAP);
            array.add(label);
        }
    }

    private static String emailType2StrLabel(int type) {
        String label = null;
        if (type == Email.TYPE_HOME) {
            label = Constants.GENERAL_LABEL_HOME;
        } else if (type == Email.TYPE_WORK) {
            label = Constants.GENERAL_LABEL_WORK;
        } else {
            label = Constants.GENERAL_LABEL_OTHER;
        }
        return label;
    }

    @SuppressWarnings("unchecked")
    private static String sendGroup(ContentValues cv, JSONObject userNameCard) throws JSONException {

        com.lzx.iteam.json.JSONArray array = new com.lzx.iteam.json.JSONArray();

        long groupId = cv.getAsLong(GroupMembership.GROUP_ROW_ID);
        String groupTitle = null;
        final HashMap<String, GroupInfo> groupList = ContactsDBReader.mGroupList;
        if (groupList != null) {
            Set<String> groupIdSet = groupList.keySet();
            Iterator<String> it = groupIdSet.iterator();
            while (it.hasNext()) {
                String groupIdKey = it.next();
                GroupInfo group = groupList.get(groupIdKey);
                if (group.mGroupID == groupId) {
                    groupTitle = group.mGroupTitle;
                }
            }
        }

        if (!StringUtil.isEmpty(groupTitle)) {
            array.add(groupTitle);
            String jsonString = array.toJSONString();
            userNameCard.put(DGROUPS, jsonString);
        }
        return groupTitle;
    }

    @SuppressWarnings("unchecked")
    private static void sendOnePostal(ContentValues cv, JSONObject userNameCard) throws JSONException {

        com.lzx.iteam.json.JSONArray array = new com.lzx.iteam.json.JSONArray();
        com.lzx.iteam.json.JSONArray addressArray = new com.lzx.iteam.json.JSONArray();

        if (cv.containsKey(StructuredPostal.CITY)) {
            String city = cv.getAsString(StructuredPostal.CITY);
            if (!StringUtil.isEmpty(city)) {
                city = Base64.encodeToString(city.getBytes(), Base64.NO_WRAP);
                addressArray.add(city);

                String label = Constants.ADDRESS_LABEL_CITY;
                label = Base64.encodeToString(label.getBytes(), Base64.NO_WRAP);
                addressArray.add(label);
            }
        }

        if (cv.containsKey(StructuredPostal.COUNTRY)) {
            String country = cv.getAsString(StructuredPostal.COUNTRY);
            if (!StringUtil.isEmpty(country)) {
                country = Base64.encodeToString(country.getBytes(), Base64.NO_WRAP);
                addressArray.add(country);

                String label = Constants.ADDRESS_LABEL_COUNTRY;
                label = Base64.encodeToString(label.getBytes(), Base64.NO_WRAP);
                addressArray.add(label);
            }
        }

        if (cv.containsKey(StructuredPostal.POSTCODE)) {
            String postcode = cv.getAsString(StructuredPostal.POSTCODE);
            if (!StringUtil.isEmpty(postcode)) {
                postcode = Base64.encodeToString(postcode.getBytes(), Base64.NO_WRAP);
                addressArray.add(postcode);

                String label = Constants.ADDRESS_LABEL_ZIP;
                label = Base64.encodeToString(label.getBytes(), Base64.NO_WRAP);
                addressArray.add(label);
            }
        }

        if (cv.containsKey(StructuredPostal.REGION)) {
            String region = cv.getAsString(StructuredPostal.REGION);
            if (!StringUtil.isEmpty(region)) {
                region = Base64.encodeToString(region.getBytes(), Base64.NO_WRAP);
                addressArray.add(region);

                String label = Constants.ADDRESS_LABEL_STATE;
                label = Base64.encodeToString(label.getBytes(), Base64.NO_WRAP);
                addressArray.add(label);
            }
        }

        if (cv.containsKey(StructuredPostal.STREET)) {
            /*
             * s.data(fieldNames[4], cv.getAsString(StructuredPostal.STREET));
             * addressArray.put(0, cv.getAsString(StructuredPostal.STREET));
             */

            String street = cv.getAsString(StructuredPostal.STREET);
            if (!StringUtil.isEmpty(street)) {
                street = Base64.encodeToString(street.getBytes(), Base64.NO_WRAP);
                addressArray.add(street);

                String label = Constants.ADDRESS_LABEL_STREET;
                label = Base64.encodeToString(label.getBytes(), Base64.NO_WRAP);
                addressArray.add(label);
            }
        }
        array.add(addressArray);

        if (cv.containsKey(StructuredPostal.TYPE) && cv.getAsInteger(StructuredPostal.TYPE) != null) {
            int type = cv.getAsInteger(StructuredPostal.TYPE);
            String label = addrType2StrLabel(type);
            label = Base64.encodeToString(label.getBytes(), Base64.NO_WRAP);
            array.add(label);
        }

        String jsonString = array.toJSONString();
        userNameCard.put(DADDRESSES, jsonString);
    }

    private static String addrType2StrLabel(int type) {
        String label = null;
        if (type == StructuredPostal.TYPE_HOME) {
            label = Constants.GENERAL_LABEL_HOME;
        } else if (type == StructuredPostal.TYPE_WORK) {
            label = Constants.GENERAL_LABEL_WORK;
        } else {
            label = Constants.GENERAL_LABEL_OTHER;
        }
        return label;
    }

    private static String sendStructuredName(ContentValues cv, JSONObject userNameCard)
            throws JSONException {
        if (cv.containsKey(StructuredName.FAMILY_NAME)) {
            String lastName = cv.getAsString(StructuredName.FAMILY_NAME);
            userNameCard.put(LAST_NAME, Base64.encodeToString(lastName.getBytes(), Base64.NO_WRAP));
        }

        if (cv.containsKey(StructuredName.GIVEN_NAME)) {
            String firstName = cv.getAsString(StructuredName.GIVEN_NAME);
            userNameCard.put(FIRST_NAME,
                    Base64.encodeToString(firstName.getBytes(), Base64.NO_WRAP));
        }

        if (cv.containsKey(StructuredName.MIDDLE_NAME)) {
            String middlename = cv.getAsString(StructuredName.MIDDLE_NAME);
            userNameCard.put(MIDDLE_NAME,
                    Base64.encodeToString(middlename.getBytes(), Base64.NO_WRAP));
        }

        String displayName = null;
        if (cv.containsKey(StructuredName.DISPLAY_NAME)) {
            displayName = cv.getAsString(StructuredName.DISPLAY_NAME);
        }

        return displayName;
    }

    private static void sendOrganization(ContentValues cv, JSONObject userNameCard) throws JSONException {

        if (cv.containsKey(Organization.TITLE)) {
            String jobtitle = cv.getAsString(Organization.TITLE);
            userNameCard.put(JOB_TITLE, Base64.encodeToString(jobtitle.getBytes(), Base64.NO_WRAP));
        }

        if (cv.containsKey(Organization.COMPANY)) {
            String organization = cv.getAsString(Organization.COMPANY);
            userNameCard.put(ORGANIZATION,
                    Base64.encodeToString(organization.getBytes(), Base64.NO_WRAP));
        }

        if (cv.containsKey(Organization.DEPARTMENT)) {
            String department = cv.getAsString(Organization.DEPARTMENT);
            userNameCard.put(DEPARTMENT,
                    Base64.encodeToString(department.getBytes(), Base64.NO_WRAP));
        }
    }

    private static void sendNickname(ContentValues cv, JSONObject userNameCard) throws JSONException {
        if (cv.containsKey(Nickname.NAME)) {
            String nickname = cv.getAsString(Nickname.NAME);
            userNameCard
                    .put(NICKNAME, Base64.encodeToString(nickname.getBytes(), Base64.NO_WRAP));
        }
    }

    @SuppressWarnings("unchecked")
    private static void sendWebpage(ContentValues cv, JSONObject userNameCard) throws JSONException {

        com.lzx.iteam.json.JSONArray array = new com.lzx.iteam.json.JSONArray();

        String urlAddress = cv.getAsString(Website.URL);
        urlAddress = Base64.encodeToString(urlAddress.getBytes(), Base64.NO_WRAP);
        array.add(urlAddress);

        if (cv.containsKey(Website.TYPE) && cv.getAsInteger(Website.TYPE) != null) {
            int type = cv.getAsInteger(Website.TYPE);
            String label = urlType2StrLabel(type);
            label = Base64.encodeToString(label.getBytes(), Base64.NO_WRAP);
            array.add(label);
        } else {
            String label = Constants.GENERAL_LABEL_OTHER;
            label = Base64.encodeToString(label.getBytes(), Base64.NO_WRAP);
            array.add(label);
        }

        String jsonString = array.toJSONString();
        userNameCard.put(DURLS, jsonString);
    }

    @SuppressWarnings("unchecked")
    private static void parseWebpage(ContentValues cv, com.lzx.iteam.json.JSONArray array) throws JSONException {

        String urlAddress = cv.getAsString(Website.URL);
        urlAddress = Base64.encodeToString(urlAddress.getBytes(), Base64.NO_WRAP);
        array.add(urlAddress);

        if (cv.containsKey(Website.TYPE) && cv.getAsInteger(Website.TYPE) != null) {
            int type = cv.getAsInteger(Website.TYPE);
            String label = urlType2StrLabel(type);
            label = Base64.encodeToString(label.getBytes(), Base64.NO_WRAP);
            array.add(label);
        } else {
            String label = Constants.GENERAL_LABEL_OTHER;
            label = Base64.encodeToString(label.getBytes(), Base64.NO_WRAP);
            array.add(label);
        }
    }

    private static String urlType2StrLabel(int type) {
        String label = null;
        if (type == Website.TYPE_HOME) {
            label = Constants.GENERAL_LABEL_HOME;
        } else if (type == Website.TYPE_WORK) {
            label = Constants.GENERAL_LABEL_WORK;
        } else if (type == Website.TYPE_HOMEPAGE) {
            label = Constants.URL_LABEL_HOMEPAGE;
        } else {
            label = Constants.GENERAL_LABEL_OTHER;
        }
        return label;
    }

    private static void sendNote(ContentValues cv, JSONObject userNameCard) throws JSONException {
        // Even when there is no local note, we must explicitly upsync an empty
        // note,
        // which is the only way to force the server to delete any pre-existing
        // note.
        String note = "";
        if (cv.containsKey(Note.NOTE)) {
            // EAS won't accept note data with raw newline characters
            note = cv.getAsString(Note.NOTE).replaceAll("\n", "\r\n");
            userNameCard.put(NOTE, Base64.encodeToString(note.getBytes(), Base64.NO_WRAP));
        }
    }

    @SuppressWarnings("unchecked")
    private static void sendPhone(ContentValues cv, JSONObject userNameCard) throws JSONException {

        com.lzx.iteam.json.JSONArray array = new com.lzx.iteam.json.JSONArray();

        String phoneNumber = cv.getAsString(Phone.NUMBER);
        phoneNumber = Base64.encodeToString(phoneNumber.getBytes(), Base64.NO_WRAP);
        array.add(phoneNumber);

        if (cv.containsKey(Phone.TYPE) && cv.getAsInteger(Phone.TYPE) != null) {
            int type = cv.getAsInteger(Phone.TYPE);
            String label = phoneType2StrLabel(type);
            label = Base64.encodeToString(label.getBytes(), Base64.NO_WRAP);
            array.add(label);
        } else {
            String label = Constants.GENERAL_LABEL_OTHER;
            label = Base64.encodeToString(label.getBytes(), Base64.NO_WRAP);
            array.add(label);
        }
        String jsonString = array.toJSONString();
        userNameCard.put(DPHONES, jsonString);
    }

    @SuppressWarnings("unchecked")
    private static void parsePhone(ContentValues cv, com.lzx.iteam.json.JSONArray array) throws JSONException {

        String phoneNumber = cv.getAsString(Phone.NUMBER);
        phoneNumber = Base64.encodeToString(phoneNumber.getBytes(), Base64.NO_WRAP);
        array.add(phoneNumber);

        if (cv.containsKey(Phone.TYPE) && cv.getAsInteger(Phone.TYPE) != null) {
            int type = cv.getAsInteger(Phone.TYPE);
            String label = phoneType2StrLabel(type);
            label = Base64.encodeToString(label.getBytes(), Base64.NO_WRAP);
            array.add(label);
        } else {
            String label = Constants.GENERAL_LABEL_OTHER;
            label = Base64.encodeToString(label.getBytes(), Base64.NO_WRAP);
            array.add(label);
        }
    }

    /**
     * use this to compatible with iOs
     *
     * @param type
     * @return
     */
    public static String phoneType2StrLabel(int type) {
        String label = null;
        switch (type) {
            case Phone.TYPE_WORK:
                label = Constants.GENERAL_LABEL_WORK;
                break;
            case Phone.TYPE_FAX_WORK:
                label = Constants.PHONE_LABEL_WORKFAX;
                break;
            case Phone.TYPE_COMPANY_MAIN:
                label = Constants.PHONE_LABEL_MAIN;
                break;
            case Phone.TYPE_HOME:
                label = Constants.GENERAL_LABEL_HOME;
                break;
            case Phone.TYPE_MOBILE:
                label = Constants.PHONE_LABEL_MOBILE;
                break;
            case Phone.TYPE_PAGER:
                label = Constants.PHONE_LABEL_PAGER;
                break;
            case Phone.TYPE_FAX_HOME:
                label = Constants.PHONE_LABEL_HOMEFAX;
                break;
            default:
                label = Constants.GENERAL_LABEL_OTHER;
                break;
        }
        return label;
    }

    public static int iPhoneType2Android(String type) {
        int androidType = 0;
        if (type.equals(Constants.GENERAL_LABEL_WORK)) {
            androidType = Phone.TYPE_WORK;
        } else if (type.equals(Constants.PHONE_LABEL_WORKFAX)) {
            androidType = Phone.TYPE_FAX_WORK;
        } else if (type.equals(Constants.PHONE_LABEL_MAIN)) {
            androidType = Phone.TYPE_COMPANY_MAIN;
        } else if (type.equals(Constants.GENERAL_LABEL_HOME)) {
            androidType = Phone.TYPE_HOME;
        } else if (type.equals(Constants.PHONE_LABEL_MOBILE)) {
            androidType = Phone.TYPE_MOBILE;
        } else if (type.equals(Constants.PHONE_LABEL_PAGER)) {
            androidType = Phone.TYPE_PAGER;
        } else if (type.equals(Constants.PHONE_LABEL_HOMEFAX)) {
            androidType = Phone.TYPE_FAX_HOME;
        }

        return androidType;

    }

    public static JSONArray contactArr2Json(long[] contactIdArr, Context context) {
        if (contactIdArr == null || contactIdArr.length < 1) {
            return null;
        }

        JSONArray jArr = new JSONArray();
        for (int i = 0; i < contactIdArr.length; i++) {
            contact2Json(contactIdArr[i], jArr, context);
        }
        return jArr;
    }

    public static JSONArray contactArr2Json(ArrayList<Long> contactIdArr, Context context) {
        if (contactIdArr == null || contactIdArr.size() < 1) {
            return null;
        }

        JSONArray jArr = new JSONArray();
        for (int i = 0; i < contactIdArr.size(); i++) {
            contact2Json(contactIdArr.get(i), jArr, context);
        }
        return jArr;
    }

    /**
     * 通过contactId将联系人转化为JsonArray 格式
     *
     * @param contactID
     * @param jArr
     * @param context
     */
    public static void contact2JsonCloudUpload(long contactID, JSONArray jArr, Context context) {

        int timesContacted = 0;
        ContactInfoNode memoryNode = PinyinSearch.getInstance(context).getContactInfo().get(contactID);
        if (memoryNode == null) {
            timesContacted = ContactsDBReader.getContactedNumber(contactID, context.getContentResolver());
        } else {
            timesContacted = memoryNode.contactedNumber;
        }

        EntityIterator ei = RawContacts.newEntityIterator(context.getContentResolver().query(
                RawContactsEntity.CONTENT_URI, null, RawContacts.CONTACT_ID + "=" + contactID,
                null, null));

        PhoneNumberArea phoneNumArea = PhoneNumberArea.getInstance(context);

        String contactName = null;
        String contactUrl = null;
        JSONArray jPhoneNum = new JSONArray();
        StringBuilder group = new StringBuilder();
        StringBuilder area = new StringBuilder();
        StringBuilder organization = new StringBuilder();
        try {
            while (ei.hasNext()) {
                Entity entity = ei.next();

                JSONObject jCloudContact = new JSONObject();
                JSONObject jNameCard = new JSONObject();

                try {
                    com.lzx.iteam.json.JSONArray phoneArray = new com.lzx.iteam.json.JSONArray();
                    com.lzx.iteam.json.JSONArray emailArray = new com.lzx.iteam.json.JSONArray();
                    com.lzx.iteam.json.JSONArray urlArray = new com.lzx.iteam.json.JSONArray();

                    for (NamedContentValues ncv : entity.getSubValues()) {
                        ContentValues cv = ncv.values;
                        String mimeType = cv.getAsString(Data.MIMETYPE);
                        if (mimeType == null)
                            continue;
                        if (mimeType.equals(StructuredName.CONTENT_ITEM_TYPE)) {
                            contactName = sendStructuredName(cv, jNameCard);
                        } else if (mimeType.equals(Phone.CONTENT_ITEM_TYPE)) {
                            // num & label
                            String num = cv.getAsString(Phone.NUMBER);
                            if (cv.containsKey(Phone.TYPE) && cv.getAsInteger(Phone.TYPE) != null) {
                                int type = cv.getAsInteger(Phone.TYPE);
                                String label = phoneType2StrLabel(type);
                                jPhoneNum.put(label);
                            } else {
                                String label = Constants.GENERAL_LABEL_OTHER;
                                jPhoneNum.put(label);
                            }
                            jPhoneNum.put(num);

                            // remark
                            String areaElement = phoneNumArea.getArea(num, false);
                            if (!TextUtils.isEmpty(areaElement) && !area.toString().contains(areaElement)) {
                                area.append(areaElement).append(',');
                            }

                            parsePhone(cv, phoneArray);
                        } else if (mimeType.equals(Email.CONTENT_ITEM_TYPE)) {
                            parseEmail(cv, emailArray);
                        } else if (mimeType.equals(Nickname.CONTENT_ITEM_TYPE)) {
                            sendNickname(cv, jNameCard);
                        } else if (mimeType.equals(Website.CONTENT_ITEM_TYPE)) {
                            // use only one URL to compatible with iOS
                            String url = cv.getAsString(Website.URL);
                            if (!TextUtils.isEmpty(url)) {
                                contactUrl = url;
                            }

                            parseWebpage(cv, urlArray);
                        } else if (mimeType.equals(StructuredPostal.CONTENT_ITEM_TYPE)) {
                            sendOnePostal(cv, jNameCard);
                        } else if (mimeType.equals(Organization.CONTENT_ITEM_TYPE)) {
                            // remark
                            String org = formatOrganization(cv);
                            if (!TextUtils.isEmpty(org)) {
                                organization.append(org).append(',');
                            }

                            sendOrganization(cv, jNameCard);
                        } else if (mimeType.equals(Note.CONTENT_ITEM_TYPE)) {
                            sendNote(cv, jNameCard);
                        }
//                        else if (mimeType.equals(Photo.CONTENT_ITEM_TYPE)) {
//                            sendPhoto(cv, jNameCard);
//                        }
                        else if (mimeType.equals(GroupMembership.CONTENT_ITEM_TYPE)) {
                            // remark
                            String groupTitle = sendGroup(cv, jNameCard);
                            if (!TextUtils.isEmpty(groupTitle)) {
                                group.append(groupTitle).append(',');
                            }
                        }
                    }

                    jNameCard.put(DURLS, urlArray.toString());
                    jNameCard.put(DEMAILS, emailArray.toString());
                    jNameCard.put(DPHONES, phoneArray.toString());
                    jNameCard.put("dataversion", Base64.encodeToString(
                            "0001".getBytes(), Base64.NO_WRAP));

                    StringBuilder remark = new StringBuilder();
                    if (area.length() > 0) remark.append(area);
                    if (group.length() > 0) remark.append(group);
                    if (organization.length() > 0) remark.append(organization);
                    if (remark.length() > 0) remark.deleteCharAt(remark.length() - 1);

                    String userId ="";
                    try {
//                        HashMap<Long, HashSet<Long>> contactId2CloudId = (HashMap<Long, HashSet<Long>>)PreferenceUtil.getInstance(context).getCloudContact(PreferenceUtil.CONTACT_ID_2_CLOUD_ID);
//                        HashSet<Long> cloudIdSet = contactId2CloudId.get(contactID);
//                        cloudId = cloudIdSet.iterator().next();
                        HashMap<String ,String> userIdMap=(HashMap<String,String>)PreferenceUtil.getInstance(context).getCloudContact(PreferenceUtil.CLOUD_PHONE_2_USEID);
                        userId=userIdMap.get(PhoneNumberArea.formatPhoneNumDisplay(jPhoneNum.getString(1)));
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    jCloudContact.put(AsynHttpClient.KEY_CONTACT_NAME, StringUtil.ensureEmptyStr(contactName));
                    jCloudContact.put(AsynHttpClient.KEY_CONTACT_REMARKS, StringUtil.ensureEmptyStr(remark.toString()));
                    jCloudContact.put(AsynHttpClient.KEY_CONTACT_PHONENUMBER, jPhoneNum);
                    jCloudContact.put(AsynHttpClient.KEY_CONTACT_URL, StringUtil.ensureEmptyStr(contactUrl));
                    jCloudContact.put(AsynHttpClient.KEY_CONTACT_NAMECARD, jNameCard);
                    jCloudContact.put(AsynHttpClient.KEY_CONTACT_DIALCOUNT, timesContacted);
                    jCloudContact.put(AsynHttpClient.KEY_USER_ID,userId);

                    jArr.put(jCloudContact);
                } catch (JSONException e) {
                    Log.e("tag", "sendContactsNoPhoto : ", e);
                }
            }
        } catch (IllegalStateException e) {
            // Caused by: java.lang.IllegalStateException: Couldn't read row
            // 367, col 9 from CursorWindow.
            // Make sure the Cursor is initialized correctly before accessing
            // data from it.
            e.printStackTrace();
        } finally {
            if (ei != null) ei.close();
        }
    }

    public static String formatOrganization(ContentValues cv) {
        StringBuilder sb = new StringBuilder();

        if (cv.containsKey(Organization.TITLE)) {
            sb.append(cv.getAsString(Organization.TITLE)).append(',');
        }

        if (cv.containsKey(Organization.COMPANY)) {
            sb.append(cv.getAsString(Organization.COMPANY)).append(',');
        }

        if (cv.containsKey(Organization.DEPARTMENT)) {
            sb.append(cv.getAsString(Organization.DEPARTMENT)).append(',');
        }

        if (sb.length() > 0) sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    public static void contact2Json(long contactID, JSONArray jArr, Context context) {
        EntityIterator ei = RawContacts.newEntityIterator(context.getContentResolver().query(
                RawContactsEntity.CONTENT_URI, null, RawContacts.CONTACT_ID + "=" + contactID,
                null, null));
        try {
            while (ei.hasNext()) {
                Entity entity = ei.next();

                JSONObject jNameCard = new JSONObject();
                try {
                    for (NamedContentValues ncv : entity.getSubValues()) {
                        ContentValues cv = ncv.values;
                        String mimeType = cv.getAsString(Data.MIMETYPE);
                        if (mimeType == null)
                            continue;
                        if (mimeType.equals(StructuredName.CONTENT_ITEM_TYPE)) {
                            sendStructuredName(cv, jNameCard);
                        } else if (mimeType.equals(Phone.CONTENT_ITEM_TYPE)) {
                            sendPhone(cv, jNameCard);
                        } else if (mimeType.equals(Email.CONTENT_ITEM_TYPE)) {
                            sendEmail(cv, jNameCard);
                        } else if (mimeType.equals(Nickname.CONTENT_ITEM_TYPE)) {
                            sendNickname(cv, jNameCard);
                        } else if (mimeType.equals(Website.CONTENT_ITEM_TYPE)) {
                            sendWebpage(cv, jNameCard);
                        } else if (mimeType.equals(StructuredPostal.CONTENT_ITEM_TYPE)) {
                            sendOnePostal(cv, jNameCard);
                        } else if (mimeType.equals(Organization.CONTENT_ITEM_TYPE)) {
                            sendOrganization(cv, jNameCard);
                        } else if (mimeType.equals(Note.CONTENT_ITEM_TYPE)) {
                            sendNote(cv, jNameCard);
                        } else if (mimeType.equals(Photo.CONTENT_ITEM_TYPE)) {
                            sendPhoto(cv, jNameCard);
                        } else if (mimeType.equals(GroupMembership.CONTENT_ITEM_TYPE)) {
                            sendGroup(cv, jNameCard);
                        }
                    }

                    jNameCard.put("dataversion",
                            Base64.encodeToString("0001".getBytes(), Base64.NO_WRAP));

                    //:
                    jArr.put(jNameCard);
                } catch (JSONException e) {
                    Log.e("tag", "sendContactsNoPhoto : ", e);
                }
            }
        } catch (IllegalStateException e) {
            // Caused by: java.lang.IllegalStateException: Couldn't read row
            // 367, col 9 from CursorWindow.
            // Make sure the Cursor is initialized correctly before accessing
            // data from it.
            e.printStackTrace();
        } finally {
            if (ei != null) ei.close();
        }
    }

    public static JSONObject getJasonContact(Context context, JSONObject paramsData) throws JSONException,
            com.lzx.iteam.json.ParseException {
        JSONObject result = new JSONObject();
        JSONObject jCloudContact = new JSONObject();
        PhoneNumberArea phoneNumArea = PhoneNumberArea.getInstance(context);

        String contactUrl = null;
        JSONArray jPhoneNum = new JSONArray();
        StringBuilder group = new StringBuilder();
        StringBuilder area = new StringBuilder();
        StringBuilder remark = new StringBuilder();

        String jobtitle = null;
        String department = null;
        String organization = null;

        String contactName = paramsData.getString("contactName");
        contactName = EncodingUtils.getString(Base64.decode(contactName, Base64.NO_WRAP), "UTF-8");
        result.put(AsynHttpClient.KEY_CONTACT_NAME, StringUtil.ensureEmptyStr(contactName));

        final JSONObject nameCard = new JSONObject(paramsData.getString("myDocument"));

        if (nameCard.has("jobtitle")) {
            jobtitle = nameCard.getString("jobtitle");
            result.put(NameCardUtil.JOB_TITLE, Base64.encodeToString(jobtitle.getBytes(), Base64.NO_WRAP));

            jobtitle = EncodingUtils.getString(Base64.decode(jobtitle, Base64.NO_WRAP), "UTF-8");
        }

        if (nameCard.has("department")) {
            department = nameCard.getString("department");
            result.put(NameCardUtil.DEPARTMENT,
                    Base64.encodeToString(department.getBytes(), Base64.NO_WRAP));

            department = EncodingUtils
                    .getString(Base64.decode(department, Base64.NO_WRAP), "UTF-8");
        }

        if (nameCard.has("organization")) {
            organization = nameCard.getString("organization");
            result.put(NameCardUtil.ORGANIZATION,
                    Base64.encodeToString(organization.getBytes(), Base64.NO_WRAP));

            organization = EncodingUtils.getString(Base64.decode(organization, Base64.NO_WRAP),
                    "UTF-8");
        }

        StringBuilder orgSb = new StringBuilder();
        if (!StringUtil.isEmpty(jobtitle)) {
            orgSb.append(jobtitle).append(',');
        }
        if (!StringUtil.isEmpty(department)) {
            orgSb.append(department).append(',');
        }
        if (!StringUtil.isEmpty(organization)) {
            orgSb.append(organization).append(',');
        }

        String photo = null;
        if (nameCard.has("image")) {
            photo = nameCard.getString("image");
            result.put(NameCardUtil.IMAGE, photo);
        }

        com.lzx.iteam.json.JSONArray phoneInfoArray = new com.lzx.iteam.json.JSONArray();
        com.lzx.iteam.json.JSONArray emailInfoArray = new com.lzx.iteam.json.JSONArray();
        com.lzx.iteam.json.JSONArray urlInfoArray = new com.lzx.iteam.json.JSONArray();

        if (nameCard.has("dphones")) {
            JSONParser parser = new JSONParser();
            String dphones = nameCard.getString("dphones");
            if (!StringUtil.isEmpty(dphones)) {
                com.lzx.iteam.json.JSONArray array = (com.lzx.iteam.json.JSONArray) parser
                        .parse(dphones);
                String[] phonesArray = null;
                int arraySize = 0;
                if (array != null)
                    arraySize = array.size();
                if (arraySize > 0) {
                    arraySize = array.size();
                    phonesArray = new String[arraySize];
                    for (int arrayIndex = 0; arrayIndex < arraySize; arrayIndex++) {
                        phonesArray[arrayIndex] = EncodingUtils.getString(
                                Base64.decode(array.get(arrayIndex).toString(), Base64.NO_WRAP),
                                "UTF-8");
                    }
                    int count = 0;
                    while (count < (arraySize - 1)) {
                        String number = phonesArray[count++];
                        String lable = phonesArray[count++];
                        phoneInfoArray.add(Base64.encodeToString(number.getBytes(), Base64.NO_WRAP));
                        phoneInfoArray.add(Base64.encodeToString(lable.getBytes(), Base64.NO_WRAP));
                        jPhoneNum.put(lable);
                        jPhoneNum.put(number);
                        String areaElement = phoneNumArea.getArea(number, false);
                        if (!TextUtils.isEmpty(areaElement) && !area.toString().contains(areaElement)) {
                            area.append(areaElement).append(',');
                        }
                    }
                    result.put(NameCardUtil.DPHONES, phoneInfoArray);
                }
            }
        }


        String demails = null;
        if (nameCard.has("demails")) {
            JSONParser parser = new JSONParser();
            demails = nameCard.getString("demails");
            if (!StringUtil.isEmpty(demails)) {
                com.lzx.iteam.json.JSONArray array = (com.lzx.iteam.json.JSONArray) parser
                        .parse(demails);
                String[] emailArray = null;
                int arraySize = 0;
                if (array != null)
                    arraySize = array.size();
                if (arraySize > 0) {
                    emailArray = new String[arraySize];
                    for (int arrayIndex = 0; arrayIndex < arraySize; arrayIndex++) {
                        emailArray[arrayIndex] = EncodingUtils.getString(
                                Base64.decode(array.get(arrayIndex).toString(), Base64.NO_WRAP),
                                "UTF-8");
                    }
                    int count = 0;
                    while (count < (arraySize - 1)) {
                        emailInfoArray.add(Base64.encodeToString(emailArray[count++].getBytes(), Base64.NO_WRAP));
                        emailInfoArray.add(Base64.encodeToString(emailArray[count++].getBytes(), Base64.NO_WRAP));
                    }
                    result.put(NameCardUtil.DEMAILS, emailInfoArray);
                }
            }
        }

        // 分组信息
        String dgroups = null;
        if (nameCard.has("dgroups")) {
            JSONParser parser = new JSONParser();
            dgroups = nameCard.getString("dgroups");
            if (!StringUtil.isEmpty(dgroups)) {
                com.lzx.iteam.json.JSONArray array = (com.lzx.iteam.json.JSONArray) parser
                        .parse(dgroups);
                int arraySize = 0;
                if (array != null)
                    arraySize = array.size();
                if (arraySize > 0) {

                    for (int arrayIndex = 0; arrayIndex < arraySize; arrayIndex++) {
                        result.put(NameCardUtil.DGROUPS, array.get(arrayIndex).toString());
                        group.append(array.get(arrayIndex).toString()).append(',');
                    }
                }
            }

        }

        if (nameCard.has("daddresses")) {
            JSONParser parser = new JSONParser();
            String address = nameCard.getString("daddresses");
            if (!StringUtil.isEmpty(address)) {
                com.lzx.iteam.json.JSONArray array = (com.lzx.iteam.json.JSONArray) parser
                        .parse(address);
                int arraySize = 0;
                if (array != null) {
                    arraySize = array.size();
                }
                int count = 0;
                while (count < (arraySize)) {
                    com.lzx.iteam.json.JSONArray innerArray = (com.lzx.iteam.json.JSONArray) parser
                            .parse(array.get(count).toString());
                    String[] addressArray = new String[innerArray.size()];
                    for (int inner = 0; inner < innerArray.size(); inner++) {
                        addressArray[inner] = EncodingUtils.getString(
                                Base64.decode(innerArray.get(inner).toString(), Base64.NO_WRAP),
                                "UTF-8");
                    }
                    String label = EncodingUtils
                            .getString(
                                    Base64.decode(array.get(count + 1).toString(), Base64.NO_WRAP),
                                    "UTF-8");
                    result.put(NameCardUtil.DADDRESSES, addressArray);
                    count += 2;
                }
            }
        }

        if (nameCard.has("durls")) {
            JSONParser parser = new JSONParser();
            String durls = nameCard.getString("durls");
            if (!StringUtil.isEmpty(durls)) {
                com.lzx.iteam.json.JSONArray array = (com.lzx.iteam.json.JSONArray) parser
                        .parse(durls);
                int arraySize = 0;
                String[] urlArray = null;
                if (array != null)
                    arraySize = array.size();
                if (arraySize > 0) {
                    urlArray = new String[arraySize];
                    for (int arrayIndex = 0; arrayIndex < arraySize; arrayIndex++) {
                        urlArray[arrayIndex] = EncodingUtils.getString(
                                Base64.decode(array.get(arrayIndex).toString(), Base64.NO_WRAP),
                                "UTF-8");
                    }

                    int count = 0;
                    while (count < (arraySize - 1)) {
                        String lable = urlArray[count++];
                        String value = urlArray[count++];
                        urlInfoArray.add(Base64.encodeToString(lable.getBytes(), Base64.NO_WRAP));
                        urlInfoArray.add(Base64.encodeToString(value.getBytes(), Base64.NO_WRAP));
                        contactUrl = value;
                    }
                    result.put(NameCardUtil.DURLS, urlInfoArray);
                }
            }
        }

        if (nameCard.has("note")) {
            String note = nameCard.getString("note");
            result.put(NameCardUtil.NOTE, note);
        }
        if (area != null && area.length() > 0) remark.append(area);
        if (group != null && group.length() > 0) remark.append(group);
        if (organization != null && organization.length() > 0) remark.append(organization);


        result.put("dataversion",
                Base64.encodeToString("0001".getBytes(), Base64.NO_WRAP));


        jCloudContact.put(AsynHttpClient.KEY_CONTACT_NAME, StringUtil.ensureEmptyStr(contactName));
        jCloudContact.put(AsynHttpClient.KEY_CONTACT_REMARKS, remark);
        jCloudContact.put(AsynHttpClient.KEY_CONTACT_PHONENUMBER, jPhoneNum);
        jCloudContact.put(AsynHttpClient.KEY_CONTACT_URL, StringUtil.ensureEmptyStr(contactUrl));
        jCloudContact.put(AsynHttpClient.KEY_CONTACT_NAMECARD, result);
        return jCloudContact;
    }


    public static long importOneContact(Context c, NameCardContact contact) {
        FreshContactObserver.LOCAL_SAVE = true;
        ContentValues emptyContentValues = new ContentValues();
        final ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
        ContentProviderOperation.Builder builder = ContentProviderOperation
                .newInsert(RawContacts.CONTENT_URI);

        builder.withValues(emptyContentValues);
        operationList.add(builder.build());

        builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
        builder.withValueBackReference(StructuredName.RAW_CONTACT_ID, 0);
        builder.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
        builder.withValue(StructuredName.DISPLAY_NAME, contact.displayName);
        builder.withValue(StructuredName.GIVEN_NAME, contact.firstName);
        builder.withValue(StructuredName.FAMILY_NAME, contact.lastName);
        builder.withValue(StructuredName.MIDDLE_NAME, contact.middleName);

        operationList.add(builder.build());

        if (contact.phoneArray.size() > 0) {
            Iterator<KeyValue> it = contact.phoneArray.iterator();
            while (it.hasNext()) {
                KeyValue obj = it.next();
                builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
                builder.withValueBackReference(Phone.RAW_CONTACT_ID, 0);
                builder.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);

                String label = obj.key;
                if (label.equalsIgnoreCase(Constants.PHONE_LABEL_MOBILE)) {
                    builder.withValue(Phone.TYPE, Phone.TYPE_MOBILE);
                } else if (label.equalsIgnoreCase(Constants.PHONE_LABEL_IPHONE)) {
                    builder.withValue(Phone.TYPE, Phone.TYPE_MOBILE);
                } else if (label.equalsIgnoreCase(Constants.PHONE_LABEL_MAIN)) {
                    builder.withValue(Phone.TYPE, Phone.TYPE_MAIN);
                } else if (label.equalsIgnoreCase(Constants.PHONE_LABEL_HOMEFAX)) {
                    builder.withValue(Phone.TYPE, Phone.TYPE_FAX_HOME);
                } else if (label.equalsIgnoreCase(Constants.PHONE_LABEL_WORKFAX)) {
                    builder.withValue(Phone.TYPE, Phone.TYPE_FAX_WORK);
                } else if (label.equalsIgnoreCase(Constants.PHONE_LABEL_PAGER)) {
                    builder.withValue(Phone.TYPE, Phone.TYPE_PAGER);
                } else if (label.equalsIgnoreCase(Constants.GENERAL_LABEL_WORK)) {
                    builder.withValue(Phone.TYPE, Phone.TYPE_WORK);
                } else if (label.equalsIgnoreCase(Constants.GENERAL_LABEL_HOME)) {
                    builder.withValue(Phone.TYPE, Phone.TYPE_HOME);
                } else if (label.equalsIgnoreCase(Constants.GENERAL_LABEL_OTHER)) {
                    builder.withValue(Phone.TYPE, Phone.TYPE_OTHER);
                } else {
                    builder.withValue(Phone.TYPE, Phone.TYPE_CUSTOM);
                    builder.withValue(Phone.LABEL, label);
                }
                builder.withValue(Phone.NUMBER, obj.value);
                operationList.add(builder.build());
            }
        }

//        if (contact.pic != null) {
//            byte[] pic = contact.pic;
//            builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
//            builder.withValueBackReference(Photo.RAW_CONTACT_ID, 0);
//            builder.withValue(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE);
//            builder.withValue(Photo.PHOTO, pic);
//            operationList.add(builder.build());
//        }

        if (contact.emailArray.size() > 0) {

            Iterator<KeyValue> it = contact.emailArray.iterator();
            while (it.hasNext()) {
                KeyValue obj = it.next();
                builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
                builder.withValueBackReference(Email.RAW_CONTACT_ID, 0);
                builder.withValue(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE);

                String label = obj.key;
                if (label.equalsIgnoreCase(Constants.GENERAL_LABEL_WORK)) {
                    builder.withValue(Email.TYPE, Email.TYPE_WORK);
                } else if (label.equalsIgnoreCase(Constants.GENERAL_LABEL_HOME)) {
                    builder.withValue(Email.TYPE, Email.TYPE_HOME);
                } else if (label.equalsIgnoreCase(Constants.GENERAL_LABEL_OTHER)) {
                    builder.withValue(Email.TYPE, Email.TYPE_OTHER);
                } else {
                    builder.withValue(Email.TYPE, Email.TYPE_CUSTOM);
                    builder.withValue(Email.LABEL, label);
                }
                builder.withValue(Email.DATA, obj.value);
                operationList.add(builder.build());
            }
        }

        if (!StringUtil.isEmpty(contact.jobTitle) || !StringUtil.isEmpty(contact.department)
                || !StringUtil.isEmpty(contact.organization)) {
            builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
            builder.withValueBackReference(Organization.RAW_CONTACT_ID, 0);
            builder.withValue(Data.MIMETYPE, Organization.CONTENT_ITEM_TYPE);
            builder.withValue(Organization.TYPE, Organization.TYPE_WORK);
            if (!StringUtil.isEmpty(contact.jobTitle)) {
                builder.withValue(Organization.TITLE, contact.jobTitle);
            }

            if (!StringUtil.isEmpty(contact.department)) {
                builder.withValue(Organization.DEPARTMENT, contact.department);
            }

            if (!StringUtil.isEmpty(contact.organization)) {
                builder.withValue(Organization.COMPANY, contact.organization);
                // orgnization.append(contact.organizationName);
            }
            operationList.add(builder.build());
        }

        // Note.CONTENT_ITEM_TYPE
        if (!StringUtil.isEmpty(contact.note)) {
            String note = contact.note;
            builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
            builder.withValueBackReference(Note.RAW_CONTACT_ID, 0);
            builder.withValue(Data.MIMETYPE, Note.CONTENT_ITEM_TYPE);
            builder.withValue(Note.NOTE, note);
            operationList.add(builder.build());
        }

        boolean groupExist = false;
        if (contact.groupNameArray != null) {
            final HashMap<String, GroupInfo> groupList = ContactsDBReader.mGroupList;
            for (int i = 0; i < contact.groupNameArray.length; i++) {
                String groupName = contact.groupNameArray[i];
                if (groupList != null) {
                    Set<String> groupIdSet = groupList.keySet();
                    Iterator<String> it = groupIdSet.iterator();
                    while (it.hasNext()) {
                        String groupIdKey = it.next();
                        GroupInfo group = groupList.get(groupIdKey);
                        if (group.mGroupTitle.equals(groupName)) {
                            // ContactsDBReader.addToGroup(this.getContentResolver(),
                            // contactId, group.mGroupID);
                            builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
                            builder.withValueBackReference(GroupMembership.RAW_CONTACT_ID, 0);
                            builder.withValue(Data.MIMETYPE, GroupMembership.CONTENT_ITEM_TYPE);
                            builder.withValue(GroupMembership.GROUP_ROW_ID, group.mGroupID);

                            operationList.add(builder.build());
                            groupExist = true;
                            break;
                        }
                    }
                    if (!groupExist) {
                        if (groupName != null && groupName.length() > 0) {
                            long groupId = ContactsDBReader.createGroup(c.getContentResolver(),
                                    groupName);
                            ContactsDBReader.resetAllContactsNumber(c);
                            builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
                            builder.withValueBackReference(GroupMembership.RAW_CONTACT_ID, 0);
                            builder.withValue(Data.MIMETYPE, GroupMembership.CONTENT_ITEM_TYPE);
                            builder.withValue(GroupMembership.GROUP_ROW_ID, groupId);

                            operationList.add(builder.build());
                        }
                    }
                }
            }
        }

        if (contact.urlArray.size() > 0) {

            Iterator<KeyValue> it = contact.urlArray.iterator();
            while (it.hasNext()) {
                KeyValue obj = it.next();
                builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
                builder.withValueBackReference(Website.RAW_CONTACT_ID, 0);
                builder.withValue(Data.MIMETYPE, Website.CONTENT_ITEM_TYPE);
                String label = obj.key;
                if (label.equals(Constants.URL_LABEL_HOMEPAGE)) {
                    builder.withValue(Website.TYPE, Website.TYPE_HOMEPAGE);
                } else if (label.equals(Constants.GENERAL_LABEL_HOME)) {
                    builder.withValue(Website.TYPE, Website.TYPE_HOME);
                } else if (label.equals(Constants.GENERAL_LABEL_WORK)) {
                    builder.withValue(Website.TYPE, Website.TYPE_WORK);
                } else if (label.equals(Constants.GENERAL_LABEL_OTHER)) {
                    builder.withValue(Website.TYPE, Website.TYPE_OTHER);
                } else {
                    builder.withValue(Website.TYPE, Website.TYPE_CUSTOM);
                    builder.withValue(Website.TYPE, label);
                }
                // values.put(Website.MIMETYPE, Website.CONTENT_ITEM_TYPE);
                // builder.withValue(Website.DISPLAY_NAME, label);
                builder.withValue(Website.DATA, obj.value);
                operationList.add(builder.build());
            }
        }

        if (contact.address != null) {
            Iterator<String> it = contact.address.keySet().iterator();
            while (it.hasNext()) {
                String label = it.next();
                String[] value = contact.address.get(label);

                if (value != null) {
                    int countInner = 0;
                    builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
                    builder.withValueBackReference(StructuredPostal.RAW_CONTACT_ID, 0);
                    builder.withValue(Data.MIMETYPE, StructuredPostal.CONTENT_ITEM_TYPE);

                    while (countInner < (value.length - 1)) {
                        String item = value[countInner++];
                        String itemLabel = value[countInner++];

                        if (itemLabel.equals(Constants.ADDRESS_LABEL_STREET)) {
                            builder.withValue(StructuredPostal.STREET, item);
                        } else if (itemLabel.equals(Constants.ADDRESS_LABEL_CITY)) {
                            builder.withValue(StructuredPostal.CITY, item);
                        } else if (itemLabel.equals(Constants.ADDRESS_LABEL_STATE)) {
                            builder.withValue(StructuredPostal.REGION, item);
                        } else if (itemLabel.equals(Constants.ADDRESS_LABEL_ZIP)) {
                            builder.withValue(StructuredPostal.POSTCODE, item);
                        } else if (itemLabel.equals(Constants.ADDRESS_LABEL_COUNTRY)) {
                            builder.withValue(StructuredPostal.COUNTRY, item);
                        } else if (itemLabel.equals(Constants.ADDRESS_LABEL_COUNTRYCODDE)) {
                            // values.put(StructuredPostal., value);
                        } else {
                        }
                    }

                    // builder.withValue(StructuredPostal.TYPE,
                    // StructuredPostal.TYPE_WORK);
                    if (label.equals(Constants.GENERAL_LABEL_WORK)) {
                        builder.withValue(StructuredPostal.TYPE, StructuredPostal.TYPE_WORK);
                    } else if (label.equals(Constants.GENERAL_LABEL_HOME)) {
                        builder.withValue(StructuredPostal.TYPE, StructuredPostal.TYPE_HOME);
                    } else if (label.equals(Constants.GENERAL_LABEL_OTHER)) {
                        builder.withValue(StructuredPostal.TYPE, StructuredPostal.TYPE_OTHER);
                    } else {
                        builder.withValue(StructuredPostal.TYPE, StructuredPostal.TYPE_CUSTOM);
                        builder.withValue(StructuredPostal.LABEL, label);
                    }
                    operationList.add(builder.build());
                }
            }
        }

        if (contact.sharedAddress != null) {
            String label = "MeetAddress";
            String[] value = contact.sharedAddress;

            if (value != null) {
                int countInner = 0;
                builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
                builder.withValueBackReference(StructuredPostal.RAW_CONTACT_ID, 0);
                builder.withValue(Data.MIMETYPE, StructuredPostal.CONTENT_ITEM_TYPE);

                while (countInner < (value.length - 1)) {
                    String item = value[countInner++];
                    String itemLabel = value[countInner++];

                    if (!StringUtil.isEmpty(itemLabel)) {
                        if (itemLabel.equals(Constants.ADDRESS_LABEL_STREET)) {
                            builder.withValue(StructuredPostal.STREET, item);
                        } else if (itemLabel.equals(Constants.ADDRESS_LABEL_CITY)) {
                            builder.withValue(StructuredPostal.CITY, item);
                        } else if (itemLabel.equals(Constants.ADDRESS_LABEL_STATE)) {
                            builder.withValue(StructuredPostal.REGION, item);
                        } else if (itemLabel.equals(Constants.ADDRESS_LABEL_ZIP)) {
                            builder.withValue(StructuredPostal.POSTCODE, item);
                        } else if (itemLabel.equals(Constants.ADDRESS_LABEL_COUNTRY)) {
                            builder.withValue(StructuredPostal.COUNTRY, item);
                        } else if (itemLabel.equals(Constants.ADDRESS_LABEL_COUNTRYCODDE)) {
                            // values.put(StructuredPostal., value);
                        } else {
                        }
                    }
                }

                builder.withValue(StructuredPostal.TYPE, StructuredPostal.TYPE_CUSTOM);
                builder.withValue(StructuredPostal.LABEL, label);
                operationList.add(builder.build());
            }
        }

//        if (contact.senderName != null) {
//            String label = "ShareBy";
//            String value = contact.senderName;
//
//            if (value != null) {
//                builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
//                builder.withValueBackReference(StructuredPostal.RAW_CONTACT_ID, 0);
//                builder.withValue(Data.MIMETYPE, StructuredPostal.CONTENT_ITEM_TYPE);
//                builder.withValue(StructuredPostal.COUNTRY, value);
//                builder.withValue(StructuredPostal.TYPE, StructuredPostal.TYPE_CUSTOM);
//                builder.withValue(StructuredPostal.LABEL, label);
//                operationList.add(builder.build());
//            }
//        }

        try {
            ContentProviderResult[] res = c.getContentResolver().applyBatch(
                    ContactsContract.AUTHORITY, operationList);
            if (res != null) {
                ContentProviderResult result = res[0];
                Uri resultUri = result.uri;
                String rawContactId = resultUri.getLastPathSegment();
                long contactId = ContactsDBReader.getContactIdByRaw(c.getContentResolver(), rawContactId);
                return contactId;
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (OperationApplicationException e) {
            e.printStackTrace();
        }
        return -1;
    }
}
